package com.android.ContactPresets;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Menu.Item;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class ContactsEdit extends Activity {

	boolean ToSave=true;
	private EditText mNameText;
	private EditText mMobileText;
	private EditText mHomeText;
	private EditText mEmailText;
	private EditText mPrefixText;
	private EditText mPreset1Text;
	private TableLayout mPresetsTable;

	private Long mRowId;
	private ContactsDbAdapter mDbHelper;

	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.contacts_edit);

		mNameText = (EditText) findViewById(R.id.name);
		mHomeText = (EditText) findViewById(R.id.home);
		mMobileText = (EditText) findViewById(R.id.mobile);
		mPrefixText = (EditText) findViewById(R.id.prefix);
		mEmailText = (EditText) findViewById(R.id.email);
		mPreset1Text = (EditText) findViewById(R.id.preset1);
		mPresetsTable = (TableLayout)findViewById(R.id.presetTable);
		Button addrowButton = (Button) findViewById(R.id.addrow);
		addrowButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				TableRow tr =new TableRow(view.getContext());
				tr.setOrientation(TableRow.HORIZONTAL );
				EditText name=new EditText(view.getContext());
				EditText value=new EditText(view.getContext());

				name.setEnabled(true);
				name.setTextSize(12);
				name.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT,
						ViewGroup.LayoutParams.FILL_PARENT));
				tr.addView(name,new TableRow.LayoutParams( TableRow.LayoutParams.FILL_PARENT,
						TableRow.LayoutParams.FILL_PARENT) );

				value.setEnabled(true);
				value.setTextSize(12);
				value.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT,
						ViewGroup.LayoutParams.FILL_PARENT));
				tr.addView(value,new TableRow.LayoutParams( TableRow.LayoutParams.FILL_PARENT,
						TableRow.LayoutParams.FILL_PARENT) );
				mPresetsTable.addView(tr,new TableLayout.LayoutParams(
						TableLayout.LayoutParams.FILL_PARENT,
						TableLayout.LayoutParams.FILL_PARENT ));
			}
		});

		mDbHelper = new ContactsDbAdapter(this);
		mDbHelper.open();
		mRowId = null;
		// IF resuming after a freeze or pause
		mRowId = icicle != null ? icicle.getLong(ContactsDbAdapter.KEY_ROWID)
				: null;
		// ELSE
		if (mRowId == null) {
			Bundle extras = getIntent().getExtras();
			mRowId = extras != null ? extras
					.getLong(ContactsDbAdapter.KEY_ROWID) : null;
		}
		populateFields();
	}

	/**
	 * Populate the text fields with data.
	 */
	private void populateFields() {
		if (mRowId != null) {
			Cursor note = mDbHelper.fetchContact(mRowId);
			startManagingCursor(note);
			mNameText.setText(note.getString(note
					.getColumnIndex(ContactsDbAdapter.KEY_NAME)));
			mHomeText.setText(note.getString(note
					.getColumnIndex(ContactsDbAdapter.KEY_HOME)));
			mMobileText.setText(note.getString(note
					.getColumnIndex(ContactsDbAdapter.KEY_MOBILE)));
			mPrefixText.setText(note.getString(note
					.getColumnIndex(ContactsDbAdapter.KEY_PREFIX)));
			mEmailText.setText(note.getString(note
					.getColumnIndex(ContactsDbAdapter.KEY_EMAIL)));
			mPreset1Text.setText(note.getString(note
					.getColumnIndex(ContactsDbAdapter.KEY_PRESET1)));

			String tmp=note.getString(note.getColumnIndex(ContactsDbAdapter.KEY_PRESET1));
			mPreset1Text.setText(tmp);
			if (!tmp.trim().equals(""))
			{
				String[] presets=tmp.split(":");
				mPresetsTable.removeAllViews();
				for (int i=0; i<presets.length;i++)
				{
					String[] presetsPair = presets[i].split("-");

					TableRow tr =new TableRow(this);
					tr.setOrientation(TableRow.HORIZONTAL );
					TextView tv=new TextView(this);
					tv.setText(presetsPair[0]);
					EditText et=new EditText(this);
					et.setEnabled(true);
					et.setTextSize(12);
					et.setText(presetsPair[1]);
					et.setLayoutParams(new ViewGroup.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT,
							ViewGroup.LayoutParams.WRAP_CONTENT));
					tr.addView(tv,new TableRow.LayoutParams( TableRow.LayoutParams.FILL_PARENT,
							TableRow.LayoutParams.WRAP_CONTENT) );
					tr.addView(et,new TableRow.LayoutParams( TableRow.LayoutParams.FILL_PARENT,
							TableRow.LayoutParams.WRAP_CONTENT) );
					mPresetsTable.addView(tr,new TableLayout.LayoutParams(
							TableLayout.LayoutParams.FILL_PARENT,
							TableLayout.LayoutParams.WRAP_CONTENT ));
				}
			}

		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, Menu.FIRST, R.string.confirm);
		menu.add(0, Menu.FIRST+1, R.string.cancel);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, Item item) {

		switch (item.getId()) {
		case Menu.FIRST:
			if (mNameText.getText().toString().trim().equals("")){
				showAlert(getText(R.string.app_name),R.drawable.contactsicon,getText(R.string.blank_name) , getText(R.string.ok) ,true);
			}
			else
			{
				ToSave=true;
				setResult(RESULT_OK);
				finish();
			}
			return true;
		case Menu.FIRST+1:
			ToSave=false;
			setResult(RESULT_CANCELED);
			finish();
			return true;
		}
		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	protected void onFreeze(Bundle outState) {
		super.onFreeze(outState);
		outState.putLong(ContactsDbAdapter.KEY_ROWID, mRowId);
	}

	@Override
	protected void onResume() {
		super.onResume();
		populateFields();
		ToSave=true;
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (ToSave==true){
			saveState();
		}
	}

	/**
	 * Saves the current text values to DB. If it's a new Contact
	 * createContact() is called else updateContact() is called.
	 */
	private void saveState() {
		String name = mNameText.getText().toString();
		String home = mHomeText.getText().toString();
		String mobile = mMobileText.getText().toString();
		String prefix = mPrefixText.getText().toString();
		String email = mEmailText.getText().toString();
		String preset1 =new String(); // = mPreset1Text.getText().toString();

		for (int i=0; i<mPresetsTable.getChildCount(); i++)
		{
			TableRow tr=(TableRow)mPresetsTable.getChildAt(i);
			for (int j=0; j< tr.getChildCount();j+=2)
			{
				TextView tv= (TextView)tr.getChildAt(j);
				EditText et= (EditText)tr.getChildAt(j+1);
				preset1 =preset1 + tv.getText().toString() + "-" + et.getText().toString() +":";
			}
		}

		if (mRowId == null) {
			long id = mDbHelper.createContact(name, home, mobile, prefix,
					email, preset1, "");
			if (id > 0) {
				mRowId = id;
			} 
		}
		else {
			mDbHelper.updateContact(mRowId, name, home, mobile, prefix, email,
					preset1, "");
		}

	}
}


